import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  baseURL: process.env.VUE_APP_BASE_API,
  // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
// 请求拦击
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.state.user.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      config.headers['Authorization'] = `Bearer ${store.state.user.token}`
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  // if the custom code is not 20000, it is judged as an error.
  function(response) {
    console.log(response, 77)
    if (response.data.success) {
      Message({
        message: response.data.message,
        type: 'success',
        duration: 5 * 1000
      })
      // 操作成功
      return response.data
    } else {
      Message({
        message: response.data.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      // 如果success为false 业务出错,直接触发reject
      // 被catch分支捕获
      return Promise.reject(new Error('请求错误'))
    }
  },
  function(error) {
    // 对响应错误做点什么
    return Promise.reject(error)
  }
  // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
)

export default service
